<template>
  <el-card class="box-card" shadow="always">
    <div slot="header" class="clearfix">
      <span>管理工具</span>
    </div>

    <el-form :model="loginInfo" ref="login" :rules="rules">
      <el-form-item prop="userName">
        <el-input
          prefix-icon="el-icon-user"
          v-model="loginInfo.userName"
          placeholder="请输入用户名"
        ></el-input>
      </el-form-item>

      <el-form-item prop="userPwd">
        <el-input
          prefix-icon="el-icon-lock"
          :type="pwdType"
          v-model="loginInfo.userPwd"
          placeholder="请输入密码"
          ><i slot="suffix" class="el-icon-view" @click="showPwd"></i
        ></el-input>
      </el-form-item>

      <el-form-item style="text-align: center">
        <el-button
          style="width: 40%"
          type="primary"
          @click="submitForm('login')"
          >登录</el-button
        >
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
export default {
  name: "Login",
  data() {
    return {
      loginInfo: {
        userName: "",
        userPwd: "",
      },
      pwdType: "password",

      rules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 6, message: "长度在 3 到 6 个字符", trigger: "blur" },
        ],
        userPwd: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, message: "密码不能小于3位", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    //formName表示验证这个表单
    submitForm(formName){
      this.$refs[formName].validate(async valid=>{
        if(!valid) return;
        const {data:res}=await this.$http.post("login",this.loginInfo);
        console.log(res);
        if(res.meta.status!=200){
          this.$message({
            message: "账号或密码错误！",
            type: "error",
          });
        }
        else{
          this.$message({
            message: "登录成功！",
            type: "success",
          });
          window.sessionStorage.setItem("token",res.meta.token);
          this.$router.replace("/main");
        }
      })
    },
    // 显示隐藏密码
    showPwd() {
      this.pwdType === "password"
        ? (this.pwdType = "")
        : (this.pwdType = "password");
      let e = document.getElementsByClassName("el-icon-view")[0];
      this.pwdType == ""
        ? e.setAttribute("style", "color:#409EFF")
        : e.setAttribute("style", "color:#c0c4cc");
    },
  },
};
</script>

<style scoped>
.box-card {
  position: absolute;
  left: 0;
  right: 0;
  width: 360px;
  margin: 80px auto;
  border-top: 20px solid #409eff;
}

.clearfix {
  text-align: center;
  position: relative;
  top: 10px;
}
.clearfix > span {
  font-size: 27;
  color: #409eff;
}
</style>